/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sdd.facades.business;

import com.sdd.entities.Orderr;
import com.sdd.facades.producer.CheckoutBusinessFacade;
import com.sdd.plains.AddressPlain;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.naming.NamingException;

/**
 *
 * @author tpgalan
 */
@Stateless
public class CheckoutBusinessFacadeBean implements CheckoutBusinessFacade, MessageListener{

    @Resource(mappedName = "jms/deliveryTopic")
    private Topic deliveryTopic;
    @Resource(mappedName = "jms/payMethodQueue")
    private Queue payMethodQueue;
    @Resource(mappedName = "jms/deliveryTopicFactory")
    private ConnectionFactory deliveryTopicFactory;
    @EJB
    OrderBusinessFacadeBean orderBusinessFacadeBean;
    MessageConsumer mc;
    MessageConsumer mcPay;
    Connection conn = null;

    Session s = null;
    Long idOrder;
    private int ccnumber;
    private int secnumber;
    
        
    @Override
    public void send(AddressPlain ap, Long id, int ccnumber, int secnumber) throws NamingException, JMSException {
        try {
            this.ccnumber = ccnumber;
            this.secnumber = secnumber;
            this.idOrder=id;
            conn = deliveryTopicFactory.createConnection();
            s = conn.createSession(true, Session.SESSION_TRANSACTED);
            Destination destination = deliveryTopic;
            MessageProducer mp = s.createProducer(destination);
            MapMessage m = s.createMapMessage();
            m.setLong("id", id);
            m.setInt("zipcode", ap.getPostCode());
            Destination tempDest = s.createTemporaryQueue();
            mc = s.createConsumer(tempDest);
            mc.setMessageListener(this);
            conn.start();
            m.setJMSReplyTo(tempDest);
            m.setJMSCorrelationID(String.valueOf(id));
            mp.send(m);
        } finally {
            if (s != null) {
                try {
                    //s.close();
                } catch (Exception e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (conn != null) {
                //conn.close();
            }
        }
    }

    @Override
    public void onMessage(Message message) {

        String messageText = null;
        try {
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                messageText = textMessage.getText();
                System.out.println("messageText: "+messageText);
                Long idDelivery = Long.parseLong(messageText);
                Orderr updateOrder = orderBusinessFacadeBean.updateOrder(this.idOrder,idDelivery);
                Long clientId = updateOrder.getCustomer().getId();
                conn = deliveryTopicFactory.createConnection();
                s = conn.createSession(true, Session.SESSION_TRANSACTED);
                Destination destination = payMethodQueue;
                MessageProducer mp = s.createProducer(destination);
                MapMessage m = s.createMapMessage();
                m.setLong("clientId", clientId);
                m.setInt("ccnumber", ccnumber);
                m.setInt("secnumber", secnumber);
                Destination tempDest = s.createTemporaryQueue();
                mcPay = s.createConsumer(tempDest);
                PayMethodResponseListener pmr = new PayMethodResponseListener(orderBusinessFacadeBean);
                pmr.orderrId = updateOrder.getId();
                mcPay.setMessageListener(pmr);
                conn.start();
                m.setJMSReplyTo(tempDest);
                m.setJMSCorrelationID(String.valueOf(clientId));
                mp.send(m);
            }

        } catch (JMSException ex) {
            Logger.getLogger(CheckoutBusinessFacadeBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}


class PayMethodResponseListener implements MessageListener{

    
    OrderBusinessFacadeBean orderBusinessFacadeBean;
    
    Long orderrId;

    public PayMethodResponseListener(OrderBusinessFacadeBean waka) {
        orderBusinessFacadeBean = waka;
    }
    
    public PayMethodResponseListener(Long orderrId) {
        this.orderrId = orderrId;
    }

    
    @Override
    public void onMessage(Message message) {
        if(message instanceof TextMessage){
                TextMessage textMessage = (TextMessage) message;
                System.out.println("Order id: "+orderrId);
                orderBusinessFacadeBean.updateOrderPaid(orderrId);
                System.out.println("Actualizado el order "+orderrId);
        }
    }
    
}